import axios from 'axios';
import { getLocale, history } from 'umi';
import { getToken } from '../token';

/**
 * 获取 Axios Custom Headers
 */
const getAxiosCustomHeaders = () => {
  return (
    localStorage.getItem(`${process.env.PROJECT_CODE}_axios_custom_headers`)?.split('##') || []
  );
};

/**
 * 设置 Axios Custom Headers
 * @param headers ['username:lvchanglong', 'name:admin']
 */
const setAxiosCustomHeaders = (headers = []) => {
  localStorage.setItem(`${process.env.PROJECT_CODE}_axios_custom_headers`, headers.join('##'));
};

// Add a request interceptor
axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  },
);

// Add a response interceptor
axios.interceptors.response.use(
  (response) => {
    // Do something with response data
    return response;
  },
  (error) => {
    // Do something with response error
    const { config, response } = error;
    if (config) {
      if (
        config.retry &&
        ['get', 'put', 'delete'].includes(config.method) &&
        (!response || (response.status >= 500 && response.status <= 599))
      ) {
        const { headers } = config;
        const xRetryCountKey = 'X-Retry-Count';
        const xRetryCountValue = parseInt(headers[xRetryCountKey] || '0', 10) + 1;
        if (xRetryCountValue <= 3) {
          return new Promise((resolve) => {
            setTimeout(
              () =>
                resolve(
                  axios({
                    ...config,
                    headers: {
                      ...headers,
                      [xRetryCountKey]: `${xRetryCountValue}`,
                    },
                  }),
                ),
              15000 * xRetryCountValue,
            );
          });
        }
      } // 重发“安全请求”
    }
    return Promise.reject(error);
  },
);

/**
 * request 方法，axios 的简单封装
 */
function request(url, config = {}) {
  getAxiosCustomHeaders().forEach((item) => {
    if (item && item.includes(':')) {
      const splits = item.split(':');
      axios.defaults.headers.common[splits[0]] = splits[1];
    }
  });

  const { method = 'get', responseType, body = {}, headers = {}, ...rest } = config;

  const newBody = /(put|post|patch)/i.test(method) ? { data: body } : { params: body }; // data 参数，在以下“请求类型”中可用：put, post, patch

  return axios
    .request({
      url, // URL 地址
      method, // 请求类型，get, post, put, delete...

      responseType: responseType || 'json', // arraybuffer, blob, document, json, text

      headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate', // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cache-Control
        'Accept-Language': `${getLocale()};q=0.9`, // 国际化“Accept-Language:zh-CN,zh;q=0.9” => zh-CN 或 en-US
        Authorization: getToken(), // 获取 token
        ...headers,
      },

      ...newBody, // 请求参数

      retry: false,

      ...rest, // 剩余参数
    })
    .then((response) => {
      return {
        success: true,
        ...response,
      };
    })
    .catch((error) => {
      const { response } = error;
      if (response) {
        const { status } = response;

        console.log(`Error${status} - ${response.config.url}`);
        console.log(response.statusText);

        if (!window.location.href.toLowerCase().includes('login') && status === 401) {
          history.push('/g/logout');
        }
      }
      return {
        success: false,
        ...response,
        data: response.data || { message: '504 Gateway Timeout' },
      };
    });
}

export { getAxiosCustomHeaders, setAxiosCustomHeaders, request };
